import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import * as jwt from 'jsonwebtoken';
import { ApiException } from 'src/common/filter/http-exception/api.exception';
import { ApiErrorCode } from 'src/common/enums/api-error-code.enum';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private reflector: Reflector) { }

  private readonly jwtSecret = 'ffjq93872';

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
      //即将调用的方法
      context.getHandler(),
      //controller类型
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }
    const request = context.switchToHttp().getRequest();

    // console.log(request.headers)
    // 从请求头或其他地方获取JWT令牌
    const token = request.headers.authorization?.replace('Bearer ', '');


    if (!token) {
      throw new ApiException('Authorization token is missing', ApiErrorCode.USER_ID_INVALID);
    }

    try {
      // 验证令牌
      const decodedToken = jwt.verify(token, this.jwtSecret);
      request.user = decodedToken; // 将令牌中的信息存储在请求对象中以便后续处理

      return true; // 令牌验证通过，允许访问
    } catch (error) {
      throw new ApiException('Invalid or expired token', ApiErrorCode.USER_ID_INVALID);
    }
  }
}
